﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Drawing.Imaging;

namespace WindowsFormsApplication1
{
    public partial class Form_umbral : Form
    {
        public Form_umbral()
        {
            InitializeComponent();
            textBox_lower.Text = trackBar_lower.Value.ToString();
            textBox_upper.Text = trackBar_upper.Value.ToString();

        }

        Bitmap image1, image2, histo;
        static int[,] binarr;
        int counter;
        
               
        private void Button1_Click(System.Object sender, System.EventArgs e) 
        {
            try {
                if (text_path.Text != "") {
                    image2 = new Bitmap(text_path.Text, true);
                    image1 = new Bitmap(image2);
                    binarr = new int[image1.Width, image1.Height];
                    try {
                        pictureBox1.Image = image1;
                        pictureBox2.Image = image2;

                        textBox_size.Text = " ( " + image1.Width + " , " + image1.Height + " ) ";

                        int ul = trackBar_lower.Value;
                        int uh = trackBar_upper.Value;
                        int x, y;
                        histo = new Bitmap(257, 132);
                        pictureBox3.Image = histo;

                        for (y = 0; y < image1.Height; y++) {
                            for (x = 0; x < image1.Width; x++) {
                                Color pixelColor = image1.GetPixel(x, y);
                                int gris = (int)((pixelColor.R * .3) + (pixelColor.G * .59) + (pixelColor.B * .11));

                                if ((gris >= ul) && (gris <= uh)) {
                                    drawHisto(gris, 130);
                                    Color newColor = Color.FromArgb(0, 0, 0);
                                    image2.SetPixel(x, y, newColor);
                                    binarr[x, y] = 1;
                                } else {
                                    Color newColor = Color.FromArgb(255, 255, 255);
                                    image2.SetPixel(x, y, newColor);
                                    binarr[x, y] = 0;
                                }
                            }
                        }

                        counter = 1;
                        for (y = 0; y < image2.Height; y++) {
                            for (x = 0; x < image2.Width; x++) {
                                if (binarr[x, y] == 1) {
                                    counter++;
                                    binarr[x, y] = counter;
                                    discovery(x, y, counter, getRandomColor());
                                }
                            }
                        }
                        textBox_objects.Text = (counter - 1).ToString();
                    } catch (Exception exc) {
                        MessageBox.Show("Ha habido un error.\n" +
                            exc.ToString());
                    }
                }
            } catch (ArgumentException) {
                MessageBox.Show("Verifica el path de la imagen.\n");
            }

        }

        private string selectTextFile(string initialDirectory) {
            OpenFileDialog dialog = new OpenFileDialog();
            dialog.Filter = "bmp files (*.bmp)|*.bmp|All files (*.*)|*.*";
            dialog.InitialDirectory = initialDirectory;
            dialog.Title = "Selecciona una linda imagen";
            return (dialog.ShowDialog() == DialogResult.OK) ? dialog.FileName : "";
        }
        
        private int discovery(int x, int y, int counter, Color color) {
            image2.SetPixel(x, y, color);
            try {
                if (binarr[x + 1, y] == 1) {
                    binarr[x + 1, y] = counter;
                    discovery(x + 1, y, counter, color);
                }
                if (binarr[x + 1, y + 1] == 1) {
                    binarr[x + 1, y + 1] = counter;
                    discovery(x + 1, y + 1, counter, color);
                }
                if (binarr[x, y + 1] == 1) {
                    binarr[x, y + 1] = counter;
                    discovery(x, y + 1, counter, color);
                }
                if (binarr[x - 1, y + 1] == 1) {
                    binarr[x - 1, y + 1] = counter;
                    discovery(x - 1, y + 1, counter, color);
                }
                if (binarr[x - 1, y] == 1) {
                    binarr[x - 1, y] = counter;
                    discovery(x - 1, y, counter, color);
                }
                if (binarr[x - 1, y - 1] == 1) {
                    binarr[x - 1, y - 1] = counter;
                    discovery(x - 1, y - 1, counter, color);
                }
                if (binarr[x, y - 1] == 1) {
                    binarr[x, y - 1] = counter;
                    discovery(x, y - 1, counter, color);
                }
            } catch (IndexOutOfRangeException) { return counter; }
            image2.SetPixel(x, y, color);
            return counter;
        }

        private Color getRandomColor() {

            Random RandomClass = new Random();
            Color newColor = Color.FromArgb(RandomClass.Next(50, 200), RandomClass.Next(50, 200), RandomClass.Next(50, 200));
            return newColor;
        }

        private void drawHisto(int col, int fila) {
            if (histo.GetPixel(col,fila).Equals(Color.FromArgb(0,0,0,0)))
                histo.SetPixel(col, fila, getRandomColor());
            else
                if (fila > 0)
                    drawHisto(col, fila-1);
        }


        private void Form1_Load(object sender, EventArgs e)
        {

        }

        private void pictureBox2_Click(object sender, EventArgs e)
        {

        }

        private void label1_Click(object sender, EventArgs e)
        {

        }

        private void groupBox1_Enter(object sender, EventArgs e)
        {

        }

        private void groupBox2_Enter(object sender, EventArgs e)
        {

        }

        private void label3_Click(object sender, EventArgs e)
        {

        }

        private void label4_Click(object sender, EventArgs e)
        {

        }

        private void openFileDialog1_FileOk(object sender, CancelEventArgs e)
        {

        }

        private void trackBar_lower_Scroll(object sender, EventArgs e)
        {
            textBox_lower.Text = trackBar_lower.Value.ToString();
            if (trackBar_lower.Value > trackBar_upper.Value)
            {
                trackBar_upper.Value = trackBar_lower.Value;
            }
            textBox_upper.Text = trackBar_upper.Value.ToString();
        }

        private void trackBar_upper_Scroll(object sender, EventArgs e)
        {
            textBox_upper.Text = trackBar_upper.Value.ToString();
            if (trackBar_upper.Value < trackBar_lower.Value)
            {
                trackBar_lower.Value = trackBar_upper.Value;
            }
            textBox_lower.Text = trackBar_lower.Value.ToString();
        }

        private void textBox_lower_TextChanged(object sender, EventArgs e) {
            try {
                trackBar_lower.Value = Int16.Parse(textBox_lower.Text);
            } catch (FormatException) {
                MessageBox.Show("Por favor introduce un No. válido.");
            }
        }

        private void textBox_upper_TextChanged(object sender, EventArgs e) {
            try {
                trackBar_upper.Value = Int16.Parse(textBox_upper.Text);
            } catch (FormatException) {
                MessageBox.Show("Por favor introduce un No. válido.");
            } catch (ArgumentOutOfRangeException) {
                MessageBox.Show("Por favor introduce un No. entre 0 y 254.");
            }
        }

        private void button_browse_Click(object sender, EventArgs e) {
            String fileName = selectTextFile("C:\\");
            text_path.Text = fileName;
            Button1_Click(sender, e);
        }



    }
}
